package com.jingdianjichi.subject.domain.service.Imp;

import com.alibaba.fastjson.JSON;
import com.jingdianjichi.subject.common.enums.IsDeleteFlagEnum;
import com.jingdianjichi.subject.domain.convert.SubjectCategoryConvert;
import com.jingdianjichi.subject.domain.convert.SubjectLabelConvert;
import com.jingdianjichi.subject.domain.entity.SubjectCategoryBO;
import com.jingdianjichi.subject.domain.entity.SubjectLabelBO;
import com.jingdianjichi.subject.domain.service.SubjectCategoryDomainService;
import com.jingdianjichi.subject.infra.basic.entity.SubjectCategory;
import com.jingdianjichi.subject.infra.basic.entity.SubjectLabel;
import com.jingdianjichi.subject.infra.basic.entity.SubjectMapping;
import com.jingdianjichi.subject.infra.basic.service.SubjectCategoryService;
import com.jingdianjichi.subject.infra.basic.service.SubjectMappingService;
import com.jingdianjichi.subject.infra.basic.service.impl.SubjectCategoryServiceImpl;
import com.jingdianjichi.subject.infra.basic.service.impl.SubjectLabelServiceImpl;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SubjectCategoryDomainImp implements SubjectCategoryDomainService {
    @Resource
    private SubjectCategoryService subjectCategoryservice;
    @Autowired
    private SubjectCategoryServiceImpl subjectCategoryService;
    @Autowired
    private SubjectMappingService subjectMappingService;
    @Autowired
    private SubjectLabelServiceImpl subjectLabelService;
    @Resource
    private ThreadPoolExecutor threadPoolExecutor;
    @Autowired
    private ThreadPoolExecutor labelThreadPool;

    @Override
    /**
     * 新增种类
     */
    public void add(SubjectCategoryBO subjectCategorybo) {
        if(log.isInfoEnabled()){
            log.info("SubjectCategoryBO:{}", subjectCategorybo);
        }
        SubjectCategory subjectCategory = SubjectCategoryConvert.INSTANCE.convertBoToCategory(subjectCategorybo);
        subjectCategoryservice.insert(subjectCategory);
    }

    /**
     * 查询分类
     * @return
     */
    @Override
    public List<SubjectCategoryBO> queryCategory(SubjectCategoryBO subjectCategorybo) {
        SubjectCategory subjectCategory = SubjectCategoryConvert.INSTANCE.convertBoToCategory(subjectCategorybo);
        List<SubjectCategory> subjectCategoryList=subjectCategoryservice.queryCategory(subjectCategory);
        List<SubjectCategoryBO> boList=SubjectCategoryConvert.INSTANCE.convertListBoToListCategory(subjectCategoryList);
        boList.forEach(bo->{
            Integer boCount=subjectCategoryService.querySubjectCount(bo.getId());
            bo.setCount(boCount);
        });
        if(log.isInfoEnabled()){
            log.info("SubjectCategoryBOList:{}", JSON.toJSONString(boList));
        }
        return boList;
    }

    /**
     * 修改分类
     * @param subjectCategoryBO
     */
    @Override
    public Boolean update(SubjectCategoryBO subjectCategoryBO) {
        SubjectCategory subjectCategory=SubjectCategoryConvert.INSTANCE.convertBoToCategory(subjectCategoryBO);
        int count=subjectCategoryService.update(subjectCategory);
        return count>0;

    }

    /**
     * 删除分类
     * @param subjectCategoryBO
     * @return
     */
    @Override
    public Boolean delete(SubjectCategoryBO subjectCategoryBO) {
        SubjectCategory subjectCategory=SubjectCategoryConvert.INSTANCE
                .convertBoToCategory(subjectCategoryBO);
        subjectCategory.setIsDeleted(IsDeleteFlagEnum.DELETED.getCode()); //逻辑删除
        int count=subjectCategoryService.update(subjectCategory);//逻辑删除 实际是更新数据库中的isdelete 字段
//        int count= subjectCategoryService.deleteById(subjectCategoryBO.getId());
        return count>0;
    }

    /**
     * 查询分类及标签
     * @param subjectCategoryBO
     * @return
     */
    @SneakyThrows
    @Override
    public List<SubjectCategoryBO> queryCategoryAndLabel(SubjectCategoryBO subjectCategoryBO) {
         //查出所有父亲种类Id为传入的id相同的种类s
        SubjectCategory subjectCategory=new SubjectCategory();
        subjectCategory.setParentId(subjectCategoryBO.getId());
        subjectCategory.setIsDeleted(IsDeleteFlagEnum.UN_DELETED.getCode());
        List<SubjectCategory> subjectCategoryList = subjectCategoryService.queryCategory(subjectCategory);
        if(log.isInfoEnabled()){
            log.info("SubjectCategoryList:{}", JSON.toJSONString(subjectCategoryList));
        }
        Map<Long,List<SubjectLabelBO>> map=new HashMap<>();
        List<SubjectCategoryBO> categoryBOList = SubjectCategoryConvert.INSTANCE.convertListBoToListCategory(subjectCategoryList);
        List<CompletableFuture<Map<Long, List<SubjectLabelBO>>>> completableFutureList = categoryBOList.stream().map(categoryBO ->
                CompletableFuture.supplyAsync(() -> getSubjectLabelBOList(categoryBO), labelThreadPool)
        ).collect(Collectors.toList());
        completableFutureList.forEach(future -> {
            Map<Long, List<SubjectLabelBO>> longListMap = null;
            try {
                longListMap = future.get();
                map.putAll(longListMap);
            } catch (Exception e) {
                e.printStackTrace();
            }

        });

//
//        List<FutureTask<Map<Long,List<SubjectLabelBO>>>> futureTaskList=new LinkedList<>();
//         //遍历种类获取符合该种类的下的所有标签，先从mapping中获取标签id再去laobel表中查出标签类  再遍历标签类制作标签类Bo
//        //线程池并发调用
//        categoryBOList.forEach(category->{
//            FutureTask<Map<Long,List<SubjectLabelBO>>> futureTask=new FutureTask<>(()->getSubjectLabelBOList(category));
//            futureTaskList.add(futureTask);
//            threadPoolExecutor.submit(futureTask);
//            Map<Long, List<SubjectLabelBO>> subjectLabelBOList = getSubjectLabelBOList(category);
//        });
//        for (FutureTask<Map<Long, List<SubjectLabelBO>>> futureTask : futureTaskList) {
//            Map<Long, List<SubjectLabelBO>> resultMap = futureTask.get();
//            if(CollectionUtils.isEmpty(resultMap)){
//                continue;
//            }
//            map.putAll(resultMap);
//        }
        categoryBOList.forEach(categoryBO->{
            subjectCategoryBO.setLabelBOList(map.get(categoryBO.getId()));
        });

        return categoryBOList;


    }

    private Map<Long,List<SubjectLabelBO>>getSubjectLabelBOList(SubjectCategoryBO category) {
        Map<Long,List<SubjectLabelBO>> labelBOMap=new HashMap<>();
        SubjectMapping subjectMapping=new SubjectMapping();
        subjectMapping.setCategoryId(category.getId());
        subjectMapping.setIsDeleted(IsDeleteFlagEnum.UN_DELETED.getCode());
        List<SubjectMapping> mappings = subjectMappingService.queryLabelById(subjectMapping);
        List<Long> labelIdList = mappings.stream().map(SubjectMapping::getLabelId).collect(Collectors.toList());

        List<SubjectLabel> labelList = subjectLabelService.batchQueryById(labelIdList);
        List<SubjectLabelBO> labelBOList=new LinkedList<>();
        labelList.forEach(label->{
            SubjectLabelBO subjectLabelBO=new SubjectLabelBO();
            subjectLabelBO.setId(label.getId());
            subjectLabelBO.setLabelName(label.getLabelName());
            subjectLabelBO.setCategoryId(label.getCategoryId());
            subjectLabelBO.setSortNum(label.getSortNum());
            labelBOList.add(subjectLabelBO);
        });
        labelBOMap.put(category.getId(), labelBOList);
        return labelBOMap;
    }
}
